package com.scau.demo.service.Impl;

import com.scau.demo.dao.StudentDao;
import com.scau.demo.entity.Student;
import com.scau.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    @Override
    public List<Student> getStudentList() {
        return studentDao.queryStudent();
    }

    @Override
    public Student queryStudentById(int id) {
        return studentDao.queryStudentById(id);
    }

    @Transactional      // 只有RuntimeException事务才会回滚
    @Override
    public boolean addStudent(Student student) {
        if(student.getName() != null && !"".equals(student.getName())){
            student.setDateEnrollment(new Date());
            try {
                int effectedNum = studentDao.insertStudent(student);
                if(effectedNum > 0){
                    return true;
                }
                else{
                    throw new RuntimeException("添加学生失败!");
                }
            }catch (Exception e){
                throw  new RuntimeException("添加学生信息失败：" + e.getMessage());
            }
        }else{
            throw new RuntimeException("学生名字不为空!");
        }
    }

    @Transactional
    @Override
    public boolean modifyStudent(Student student) {
        if(student.getId() != null && student.getId() > 0){
            try {
                int effectedNum = studentDao.updateStudent(student);
                if(effectedNum > 0){
                    return true;
                }
                else{
                    throw new RuntimeException("修改学生失败!");
                }
            }catch (Exception e){
                throw  new RuntimeException("修改学生信息失败：" + e.getMessage());
            }
        }else{
            throw new RuntimeException("学生ID不能为空!");
        }
    }


    @Transactional
    @Override
    public boolean deleteStudent(int id) {
        if(id > 0){
            try{
                int effectedNum = studentDao.deleteStudent(id);
                if(effectedNum > 0){
                    return true;
                }else{
                    throw new RuntimeException("删除学生信息失败！");
                }
            } catch (Exception e) {
                throw  new RuntimeException("删除学生信息失败：" + e.getMessage());
            }
        }else {
            throw  new RuntimeException("学生ID不能为空！");
        }
    }
}